<template>
  <div id="operate-orderform">
    <el-container style="overflow-x:hidden;overflow-y:hidden; height:100%;">
      <el-scrollbar
        style="width:100%;height:100%;white-space: nowrap;"
        @mousewheel.native="wheel"
        ref="roleRoll"
        class="roleRoll"
      >
        <el-header>
          <!-- 查询开始 -->
          <el-form
            :inline="true"
            :model="formInline"
            class="demo-form-inline"
            style="margin-top:20px"
          >
            <el-form-item>
              <el-input
                v-model.trim="formInline.orderNo"
                placeholder="输入评论ID"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-select
                v-model="formInline.status"
                placeholder="请选择订单状态"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="onSubmit()"
                icon="el-icon-search"
                clearable
                v-permission="'operation:order:list'"
                >查询</el-button
              >
            </el-form-item>
            <br />
            <el-form-item>
              <el-date-picker
                v-model="formInline.gmtStart"
                type="datetime"
                placeholder="选择开始日期时间"
                value-format="timestamp"
              >
              </el-date-picker>
              至
              <el-date-picker
                v-model="formInline.gmtEnd"
                type="datetime"
                placeholder="选择结束日期时间"
                value-format="timestamp"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-select v-model="formInline.export" placeholder="待出库">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-download"
                @click="derive()"
                >导出</el-button
              >
            </el-form-item>
          </el-form>
          <!-- 查询结束 -->
        </el-header>

        <el-main>
          <el-table
            :data="tableData"
            style="width: 100%;"
            :default-sort="{ prop: 'date', order: 'descending' }"
            align="center border show-summary"
            border
            :cell-class-name="tableRowClassName"
          >
            <!-- 列表数据 -->
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-form label-position="left" class="demo-table-expand">
                  <el-form-item label="联系人">
                    <span>{{ props.row.consignee }}</span>
                  </el-form-item>
                  <el-form-item label="联系电话">
                    <span>{{ props.row.phone }}</span>
                  </el-form-item>
                  <el-form-item label="客服备注">
                    <span>{{ props.row.adminMono | adminMono }}</span>
                  </el-form-item>
                  <el-form-item label="退款原因" v-if="props.row.status == 60">
                    <span>{{ props.row.adminMono }}</span>
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column prop="orderNo" label="订单编号" width="180">
            </el-table-column>
            <el-table-column prop="userId" label="用户ID"> </el-table-column>
            <el-table-column prop="status" label="订单状态" width="120">
              <template slot-scope="scope">
                <el-tag>
                  {{ scope.row.status | status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="payChannel" label="支付渠道" width="100">
              <template slot-scope="scope">
                <el-tag>
                  {{ scope.row.payChannel | payChannel }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="actualPrice" label="订单金额" width="100">
              <template slot-scope="scope">
                {{ scope.row.actualPrice | actualPrice }}
              </template>
            </el-table-column>
            <el-table-column prop="gmtCreate" label="创建时间" width="140">
              <template slot-scope="scope">{{
                scope.row.gmtCreate | formatDate
              }}</template>
            </el-table-column>
            <el-table-column prop="shipCode" label="物流渠道" width="120">
              <template slot-scope="scope">
                <el-tag>
                  {{ scope.row.shipCode | shipCode }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="物流单号" width="200" prop="shipNo">
            </el-table-column>
            <el-table-column label="备注" width="200"> </el-table-column>
            <el-table-column label="操作" width="300">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  @click="particulars(scope.$index, scope.row)"
                  v-permission="'operation:order:detail'"
                  >详情</el-button
                >
                <el-button
                  size="mini"
                  type="primary"
                  v-if="scope.row.status == 20"
                  @click="distribution(scope.$index, scope.row)"
                  >配送单</el-button
                >
                <el-button
                  size="mini"
                  type="primary"
                  v-if="scope.row.status == 20"
                  @click="compile(1, scope.row)"
                  v-permission="'operation:order:ship'"
                  >发货</el-button
                >
                <el-button
                  size="mini"
                  type="primary"
                  v-if="scope.row.status == 60"
                  @click="refunds(scope.row)"
                  v-permission="'operation:order:refund'"
                  >退款</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-main>
        <el-footer>
          <!-- 底部页数 -->
          <paging :paging="paging" :onSubmit="onSubmit"></paging>
        </el-footer>
      </el-scrollbar>
      <!-- 滚动组件结束 -->
    </el-container>
    <!-- 主要内容结束 -->
    <el-dialog title="订单详情" :visible.sync="dialogTableVisible">
      <!-- 对话框详情 -->
      <el-form label-position="right">
        <el-form-item label="订单编号">
          {{ roledata.orderNo }}
        </el-form-item>
        <el-form-item label="用户Id">
          {{ roledata.userId }}
        </el-form-item>
        <el-form-item label="订单渠道">
          {{ roledata.channel }}
        </el-form-item>
        <el-form-item label="订单状态">
          <el-tag>
            {{ roledata.status | status }}
          </el-tag>
        </el-form-item>
        <el-form-item label="支付渠道">
          <el-tag>
            {{ roledata.payChannel | payChannel }}
          </el-tag>
        </el-form-item>
        <el-form-item label="用户留言"> </el-form-item>
        <el-form-item label="客服备注">
          {{ roledata.adminMono }}
          <el-button type="primary" icon="el-icon-edit" @click="compile(0)"
            >编辑</el-button
          >
        </el-form-item>
        <el-form-item label="配送费用">
          免运费
        </el-form-item>
        <el-form-item label="收货信息">
          （收货人）{{ roledata.consignee }}（手机号）{{
            roledata.phone
          }}
          （地址）{{ roledata.province }}{{ roledata.city }}{{ roledata.county
          }}{{ roledata.address }}
        </el-form-item>
        <el-form-item label="商品信息">
          <el-table :data="roledata.skuList" border style="width: 100%">
            <el-table-column prop="spuTitle" label="名称"> </el-table-column>
            <el-table-column prop="title" label="规格"> </el-table-column>
            <el-table-column prop="num" label="商品数量"> </el-table-column>
            <el-table-column label="总价（单价*数量）">
              <template slot-scope="scope">
                {{ scope.row.price | totalPrice(scope.row.num) }}
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="dialogVisible">
      <!-- 对话框发货表单 -->
      <el-form
        label-position="right"
        :model="ruleForm"
        ref="ruleForm"
        label-width="130px"
        :rules="rules"
      >
        <el-form-item label="快递公司" prop="shipCode" v-if="title == '发货'">
          <el-select v-model="ruleForm.shipCode" placeholder="请选择活动区域">
            <el-option
              v-for="item in company"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="快递编号" prop="shipNo" v-if="title == '发货'">
          <el-input v-model="ruleForm.shipNo" style="width:300px"></el-input>
        </el-form-item>
        <el-form-item label="等级" prop="adminMonoLevel" v-if="title != '发货'">
          <el-radio-group v-model="ruleForm.adminMonoLevel" style="width:300px">
            <el-radio :label="0">无色</el-radio>
            <el-radio :label="1">绿色</el-radio>
            <el-radio :label="2">橙黄</el-radio>
            <el-radio :label="3">红色</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="内容" prop="adminMono" v-if="title != '发货'">
          <el-input v-model="ruleForm.adminMono" style="width:300px"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog title="退款" :visible.sync="dialogRefundVisible">
      <!-- 对话框退款 -->
      <el-form
        label-position="left"
        label-width="100px"
        style="margin-left: 50px;width: 400px"
      >
        <el-form-item label="tips">
          <div>允许退款后钱会退回对方账户，请确认您已经收到退货</div>
        </el-form-item>
        <el-form-item label="操作">
          <el-radio-group v-model="refund">
            <el-radio :label="0">拒绝退款</el-radio>
            <el-radio :label="1">允许退款</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="金额" v-if="refund == 1">
          <el-input v-model="ruleForm.money" style="width:300px"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogRefundVisible = false">取 消</el-button>
        <el-button type="primary" @click="refunding()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import orderform from "@/api/orderform";
import Paging from "../../components/Paging";
import TimeDate from "@/util/TimeDate";
export default {
  components: {
    Paging,
  },
  data() {
    return {
      options: [
        //选择状态
        {
          value: 10,
          label: "未付款",
        },
        {
          value: 20,
          label: "待出库",
        },
        {
          value: 30,
          label: "待收货",
        },
        {
          value: 40,
          label: "待评价",
        },
        {
          value: 50,
          label: "已完成",
        },
        {
          value: 60,
          label: "退款中",
        },
        {
          value: 70,
          label: "已退款",
        },
        {
          value: 80,
          label: "已取消",
        },
        {
          value: 90,
          label: "已取消(系统)",
        },
      ],
      company: [
        //选择物流公司
        {
          value: 0,
          label: "无需物流公司",
        },
        {
          value: "SF",
          label: "顺丰速运",
        },
        {
          value: "BS",
          label: "百世快递",
        },
        {
          value: "ZTO",
          label: "中通快递",
        },
        {
          value: "ST",
          label: "申通快递",
        },
        {
          value: "YT",
          label: "圆通速递",
        },
        {
          value: "YD",
          label: "韵达速递",
        },
        {
          value: "YZPY",
          label: "邮政快递包裹",
        },
        {
          value: "EMS",
          label: "EMS",
        },
        {
          value: "TT",
          label: "天天快递",
        },
        {
          value: "JD",
          label: "京东快递",
        },
        {
          value: "YS",
          label: "优速快递",
        },
        {
          value: "DB",
          label: "德邦快递",
        },
        {
          value: "ZJ",
          label: "宅急送",
        },
        {
          value: "TNT",
          label: "TNT快递",
        },
      ],
      formInline: {
        //查询数据
        orderNo: "", //订单号
        status: "", //订单状态
        gmtStart: "", //开始日期时间
        gmtEnd: "", //结束日期时间
        export: "", //订单状态导出
      },

      ruleForm: {
        shipCode: 0, //快递公司
        shipNo: "", //快递编号
        adminMono: "", //客服备注
        adminMonoLevel: "", //客服备注状态
        money: "", //金额
      },
      rules: {
        shipCode: [
          { required: true, message: "请选择快递公司", trigger: "change" },
        ],
      },
      refund: 0, //是否退款
      roledata: "", //选中的数据的详情
      pitchOn: "", //选中的数据
      index: "", //选中的下标
      tableData: [], //后台全部列表数据
      arr: [], //查询详情的数组
      dialogTableVisible: false, //对话框表单的隐藏显示
      dialogVisible: false, //对话框发货的隐藏显示
      dialogRefundVisible: false, //对话框退款的隐藏显示
      title: "发货", //对话框的名字
      paging: {
        currentPage: 1, //出现的页数
        pagesize: 10, //    每页的数据
        total: 0, //总条数
      },
    };
  },
  created: function() {
    //一开始的渲染数据
    this.onSubmit();
  },
  filters: {
    //过滤
    formatDate(value) {
      //转换时间戳
      return TimeDate.format(new Date(value), "MM月dd日hh时mm分");
    },
    status(value) {
      switch (value) {
        case 10:
          value = "未付款";
          break;
        case 20:
          value = "待出库";
          break;
        case 30:
          value = "待收货";
          break;
        case 40:
          value = "待评价";
          break;
        case 50:
          value = "已完成";
          break;
        case 60:
          value = "退款中";
          break;
        case 70:
          value = "已退款";
          break;
        case 80:
          value = "已取消";
          break;
        default:
          value = "已取消(系统)";
          break;
      }
      return value;
    },
    payChannel(value) {
      switch (value) {
        case "WX":
          value = "微信支付";
          break;
        case "OFFLINE":
          value = "线下支付";
          break;
        default:
          value = "未支付";
          break;
      }
      return value;
    },
    actualPrice(value) {
      return "￥" + value / 100;
    },
    totalPrice(value, data) {
      return (value * data) / 100;
    },
    adminMono(value) {
      if (value == undefined) {
        value = "无";
      }
      return value;
    },
    shipCode(value) {
      switch (value) {
        case "SF":
          value = "顺丰快递";
          break;
        case "BS":
          value = "百世快递";
          break;
        case "ZTO":
          value = "中通快递";
          break;
        case "ST":
          value = "申通快递";
          break;
        case "YT":
          value = "圆通快递";
          break;
        case "YD":
          value = "韵达快递";
          break;
        case "YZPY":
          value = "邮政快递包裹";
          break;
        case "EMS":
          value = "EMS";
          break;
        case "TT":
          value = "天天快递";
          break;
        case "JD":
          value = "京东快递";
          break;
        case "YS":
          value = "优速快递";
          break;
        case "DB":
          value = "德邦快递";
           break;
        case "ZJ":
          value = "宅急送";
          break;
        case "TNT":
          value = "TNT快递";
          break;
        default:
          value = "未发货";
          break;
      }
      return value;
    },
  },
  methods: {
    onSubmit() {
      //查询
      let that = this;
      let data = Object.assign(that.formInline, {
        page: that.paging.currentPage,
        limit: that.paging.pagesize,
      });
      orderform
        .listInquire(data) //查询接口封装
        .then((res) => {
          that.tableData = res.data.data.items; //获取数据赋值
          that.paging.total = res.data.data.total; //总条数
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    particulars(index, row) {
      //详情
      this.dialogTableVisible = true;
      this.index = index;
      orderform.detailInquire({ orderId: row.id }).then((res) => {
        this.roledata = res.data.data;
      });
    },
    distribution(index, row) {
      //配送单
      let that = this;
      console.log(index, row);
      orderform.detailInquire({ orderId: row.id }).then((res) => {
        let delivery = res.data.data;
        let arrs = delivery.skuList[0];
        let site = row.province + row.city + row.county + row.address;
        let siteScope = row.province + row.city + row.county;
        that.arr = [];
        that.arr.push(
          Object.assign(delivery, arrs, row, {
            site: site,
            siteScope: siteScope,
          })
        );
        that.exports();
      });
    },
    compile(index, row) {
      //放货和编辑
      this.pitchOn = row;
      this.dialogVisible = true;
      if (index == 1) {
        this.title = "发货";
      } else {
        this.title = "编辑";
        this.ruleForm.adminMonoLevel = this.roledata.adminMonoLevel;
        this.ruleForm.adminMono = this.roledata.adminMono;
        console.log(this.title, this.roledata);
      }
    },
    submitForm(formName) {
      //表单
      let that = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.dialogVisible = false;
          if (that.title == "发货") {
            let data = Object.assign(
              { orderNo: that.pitchOn.orderNo },
              that.ruleForm
            );
            console.log(data);
            orderform.ship(data).then((res) => {
              //发货接口
              if (res.data.errmsg == "成功") {
                that.topTips(res.data.errmsg, "success");
                that.onSubmit();
              } else {
                that.topTips(res.data.errmsg, "error");
              }
            });
          } else {
            console.log(that.roledata);
            orderform
              .editAdminMono({
                orderId: that.roledata.id,
                level: that.ruleForm.adminMonoLevel,
                mono: that.ruleForm.adminMono,
              })
              .then((res) => {
                if (res.data.errmsg == "成功") {
                  that.topTips(res.data.errmsg, "success");
                  that.onSubmit();
                } else {
                  that.topTips(res.data.errmsg, "error");
                }
              });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    derive() {
      //导出按钮的导出
      let that = this;
      let datas = Object.assign(this.formInline, {
        status: this.formInline.export,
      });
      orderform.queryToExcel(datas).then((res) => {
        console.log(res);
        if (res.data.errmsg == "成功") {
          if (res.data.data != undefined) {
            that.topTips(res.data.errmsg, "success");
            let delivery = res.data.data;
            for (const i in delivery) {
              let arrs = delivery[i].skuList[0];
              let site =
                delivery[i].province +
                delivery[i].city +
                delivery[i].county +
                delivery.address;
              let siteScope =
                delivery[i].province + delivery[i].city + delivery[i].county;
              let dispatching = Object.assign(arrs, delivery[i], {
                site: site,
                siteScope: siteScope,
              });
              that.arr.push(dispatching);
            }
            setTimeout(function() {
              that.exports();
            }, 900);
          } else {
            that.topTips("没有信息可以打印", "error");
          }
        } else {
          that.topTips(res.data.errmsg, "error");
        }
      });
      console.log(that.arr);
    },
    exports() {
      //导出
      let that = this;
      // console.log(this.tableData)
      console.log(that.arr);
      require.ensure([], () => {
        let { export_json_to_excel } = require("@/util/Export2Excel");
        let tHeader = [
          "订单编号",
          "商品名称",
          "规格",
          "单位",
          "配送数量",
          "配送地址",
          "收货人",
          "联系方式",
          "区域划分",
          "客服备注",
          "用户备注",
        ];
        let filterVal = [
          "orderNo",
          "spuTitle",
          "title",
          "unit",
          "num",
          "site",
          "consignee",
          "phone",
          "siteScope",
          "adminMono",
          "",
        ];
        let list = that.arr;
        let data = that.formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, "订单信息");
        that.arr = []; //运行后清除数组
      });
    },

    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
    tableRowClassName({ row, columnIndex }) {
      //带状态表格
      if (row.adminMonoLevel === 1 && columnIndex == 1) {
        return "success-row";
      } else if (row.adminMonoLevel === 2 && columnIndex == 1) {
        return "warning-row";
      } else if (row.adminMonoLevel === 3 && columnIndex == 1) {
        return "error-row";
      }
      return "";
    },
    refunds(row) {
      //退款按钮
      this.pitchOn = row;
      this.dialogRefundVisible = true;
    },
    refunding() {
      //退款
      let that = this;
      orderform
        .refund({
          orderNo: that.pitchOn.orderNo,
          type: that.refund,
        })
        .then((res) => {
          if (res.data.errmsg == "成功") {
            that.dialogRefundVisible = false;
            that.topTips(res.data.errmsg, "success");
            that.onSubmit();
          } else {
            that.topTips(res.data.errmsg, "error");
          }
        });
    },
    wheel(e) {
      //滚动事件
      e = e || window.event;
      if (e.wheelDelta) {
        if (e.wheelDelta < 0) {
          //控制滚动的方向
          //向下
          this.$refs.roleRoll.wrap.scrollTop += 20;
        } else {
          this.$refs.roleRoll.wrap.scrollTop -= 20;
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
#operate-orderform {
  //内容填满
  height: 100%;
}
.el-main {
  line-height: 0px !important;
}
.concer-input {
  //查询文本框
  width: 25%;
  margin-right: 10px;
}
.el-header {
  //查询布局
  line-height: 52px;
  height: auto !important;
}
.demo-form-inline {
  //查询布局
  white-space: pre-line;
}
.demo-form-inline > div {
  //查询布局
  margin-bottom: 0px;
}
</style>

<style>
.el-dialog__header,
.dialog-footer,
.el-tree-node__label,
.el-dialog__footer,
.el-checkbox,
.custom-tree-node {
  /*对话框的行高*/
  line-height: 0px;
}
.cell {
  /*列表居中*/
  text-align: center;
}
.el-table .warning-row {
  background: #e6a23c;
}
.el-table .success-row {
  background: #67c23a;
}
.el-table .error-row {
  background: #f56c6c;
}
::-webkit-scrollbar {
  /*对话框的隐藏滚动条但是可以滚动，滚动条的宽度*/
  width: 0px !important;
}
</style>
